package com.szly.phm.admin.controller;

import com.szly.phm.admin.utils.CustomResponse;
import com.szly.phm.common.entity.result.RootResponse;
import com.szly.phm.common.mapper.ScTeachDataMapper;
import io.swagger.annotations.Api;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.UUID;

@RestController
@Validated
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
@RequestMapping("/pc/file")
@Api(tags = "文件上传")
public class FileController {
    /**
     * @Description
     * @Author 刘阳
     * @Date 2018-05-15 14:04
     */
    @Value("${web.upload-path}")
    private String uploadPath;
    private final ScTeachDataMapper scTeachDataMapper;
        @PostMapping("/upload")
        @ResponseBody
        @CustomResponse
        public RootResponse upload(@RequestParam("file") MultipartFile file,HttpServletRequest request) {
       long time= new Date().getTime();
            File folder = new File(uploadPath+"static");
            if (!folder.isDirectory()) {
                folder.mkdirs();
            }
            // 对上传的文件重命名，避免文件重名
            String oldName = file.getOriginalFilename();
            String newName = time+UUID.randomUUID().toString()
                    + oldName.substring(oldName.lastIndexOf("."), oldName.length());
            File dest = new File(folder +"/"+ newName);
            try {
                file.transferTo(dest);
                // 返回上传文件的访问路径
                String filePath = request.getScheme() + "://" + request.getServerName()
                        + ":" + request.getServerPort() +"/static/"  + newName;
                return RootResponse.success(newName);
                } catch (IOException e) {
                }
            return RootResponse.error("上传失败");
        }





}
